﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Management_DanhSachThuoc : System.Web.UI.UserControl
{

    public string CurrentName
    {
        get
        {
            return liThuoc.SelectedItem.ToString();
        }
    }
    public int SelectedID
    {
        get
        {
            return Int32.Parse(liThuoc.SelectedValue);
        }
    }

    public string CurrentUnitType
    {
        get
        {
            int id = SelectedID;
            return getUnitTypeByID(id);
        }
    }

    public void loadAllType()
    {
        SqlConnection conn = new SqlConnection(GlobalConstant.CONNECTION_STRING);
        conn.Open();
        string sql = "SELECT ID, Name, UnitType FROM tbDrug ORDER BY Name";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlDataReader reader = cmd.ExecuteReader();
        liThuoc.DataSource = reader;
        liThuoc.DataTextField = "Name";
        liThuoc.DataValueField = "ID";
        liThuoc.DataBind();
        reader.Close();
        conn.Close();
        
    }

    public void loadTypeByIDWard(int IDWard)
    {
        SqlConnection conn = new SqlConnection(GlobalConstant.CONNECTION_STRING);
        conn.Open();
        string sql = "SELECT IDDrug, tbDrug.[Name] FROM tbWardDrug INNER JOIN tbDrug ON tbWardDrug.[IDDrug]=tbDrug.[ID] WHERE IDWard="+IDWard+" ORDER BY Name";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlDataReader reader = cmd.ExecuteReader();
        liThuoc.DataSource = reader;
        liThuoc.DataTextField = "Name";
        liThuoc.DataValueField = "IDDrug";
        liThuoc.DataBind();
        reader.Close();        
        conn.Close();
    }

    public int getIDDrugByName(string DrugName)
    {
        int result=0;
        SqlConnection conn = new SqlConnection(GlobalConstant.CONNECTION_STRING);
        conn.Open();
        string sql = "SELECT [ID] FROM tbDrug WHERE Name='"+DrugName+"'";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader.Read())
        {
            result = reader.GetInt32(0);
        }
        reader.Close();
        conn.Close();
        return result;
    }

    private string getUnitTypeByID(int id)
    {
        string result = "";
        SqlConnection conn = new SqlConnection(GlobalConstant.CONNECTION_STRING);
        conn.Open();
        string sql = "SELECT [UnitType] FROM tbDrug WHERE ID='" + id + "'";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader.Read())
        {
            result = reader.GetString(0);
        }
        reader.Close();
        conn.Close();
        return result;
    }

}